package cn.yd.rb.service.serviceimpl;




import cn.yd.rb.mapper.GradeMapper;

import cn.yd.rb.mapper.NovelMapper;
import cn.yd.rb.po.Grade;
import cn.yd.rb.po.GradeExample;
import cn.yd.rb.po.Novel;
import cn.yd.rb.po.NovelExample;
import cn.yd.rb.service.GradeService;
import org.apache.jasper.tagplugins.jstl.core.ForEach;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class GradeServiceImpl implements GradeService {

    @Autowired
    private GradeMapper gradeMapper;

    @Autowired
    private NovelMapper novelMapper;
    @Override
    public Grade findGrade(Integer novel_id, Integer userId) {
        GradeExample gradeExample = new GradeExample();
        GradeExample.Criteria criteria = gradeExample.createCriteria();
        criteria.andNovelidEqualTo(novel_id);
        criteria.andUseridEqualTo(userId);
        List<Grade> grade = gradeMapper.selectByExample(gradeExample);
        if(grade.isEmpty()){
            return null;
        }else{
            return grade.get(0);
        }
    }

    @Override
    public void insertGrade(Grade grade) {
        //插入评分
        gradeMapper.insertSelective(grade);
        //重新计算评分
        GradeExample gradeExample = new GradeExample();
        GradeExample.Criteria criteria = gradeExample.createCriteria();
        criteria.andNovelidEqualTo(grade.getNovelid());
        List<Grade> gradeList = gradeMapper.selectByExample(gradeExample);
        float score = 0;
        for (Grade gradeRes: gradeList) {
            score += gradeRes.getScore();
        }
        float newScore = score/gradeList.size();
        NovelExample novelExample = new NovelExample();
        NovelExample.Criteria criteria2 = novelExample.createCriteria();
        criteria2.andIdEqualTo(grade.getNovelid());
        Novel novel = novelMapper.selectByPrimaryKey(grade.getNovelid());
        novel.setAvgscore(newScore);
        novelMapper.updateByPrimaryKey(novel);
    }
}
